<?php


namespace plugin\exportcenter\app\logic;


use app\common\logic\BaseLogic;
use Carbon\Carbon;
use core\utils\Time;
use core\utils\WsUtil;
use GatewayWorker\Lib\Gateway;
use plugin\exportcenter\app\model\Export as ExportModel;

class ExportLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new ExportModel();
    }

    /**
     * 关闭超过10分钟没完成的导出任务(有可能是队列消费失败了)
     */
    public function closeExport()
    {
        $this->model->where([
            ['create_time', '<=', Carbon::now()->subMinutes(10)->format(Time::DATE_TIME)],
            ['status', "=", ExportModel::STATUS_NORMAL]
        ])
            ->update([
                'status' => ExportModel::STATUS_CANCEL
            ]);
    }

    /**
     * 修改导出开始状态
     * @param $id
     */
    public function updateExportStart($id)
    {
        ExportModel::where(['id' => $id])->update([
            "status" => ExportModel::STATUS_EXPORT_ING
        ]);
    }

    /**
     * 修改导出成功
     * @param $id
     * @param $url
     */
    public function updateExportSuccess($id, $url)
    {
        ExportModel::where(['id' => $id])->update([
            "status" => ExportModel::STATUS_SUCCESS,
            "url" => $url,
            'export_time' => Time::now(),
        ]);
        $uid = ExportModel::where(['id' => $id])->value("created_id");
        $this->sendGateway($uid, [
            'title' => "您的导出已完成,请前往导出中心下载",
            "id" => $id
        ]);
    }

    /**
     * 发生websocket消息
     * @param $uid
     * @param $data
     */
    public function sendGateway($uid, $data)
    {
        if (config("plugin.webman.gateway-worker.app.enable")) {
            if (Gateway::isUidOnline($uid)) {
                Gateway::sendToUid($uid, WsUtil::encode("export", $data));
            }
        }
    }

    /**
     * 修改导出失败状态
     * @param $id
     * @param string $error_msg
     */
    public function updateExportError($id, $error_msg = "")
    {
        ExportModel::where(['id' => $id])->update([
            "status" => ExportModel::STATUS_ERROR,
            'export_time' => Time::now(),
            "error_msg" => $error_msg,
        ]);
        $uid = ExportModel::where(['id' => $id])->value("created_id");
        $this->sendGateway($uid, [
            'title' => "您的导出失败了,请重试",
            "id" => $id
        ]);
    }



}